package ${packageName}.service;

import ${packageName}.pojo.${modelName};
import ${packageName}.mapper.${mapperName};
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import ${packageName}.result.Pager;
import ${packageName}.result.Result;
import ${packageName}.result.Parameter;
import ${packageName}.result.ParameterUtil;
import java.util.*;
import java.util.List;
import ${packageName}.util.PoiExport;
import ${packageName}.util.Tool;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import com.sp.util.PoiReadUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.PrintWriter;
import org.springframework.web.multipart.MultipartFile;

import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import javax.servlet.http.HttpServletResponse;

@Service
public class ${serviceImplName} implements ${serviceName}{

@Resource
private ${mapperName} ${mapperName?uncap_first};
@Resource
private HttpServletResponse response;
/**
*增加${remarksTable}数据
**/
public  int insert${modelName}(${modelName} record)throws Exception{
int totalRecords=0;

<#if plugin.enableMybatisplus>
    totalRecords+=${mapperName?uncap_first}.insert(record);
<#else >
    totalRecords+=${mapperName?uncap_first}.insert${modelName}(record);
</#if>

return totalRecords;
}

<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
    /**
    *删除${remarksTable}数据
    **/
    public  int delete${modelName}ByPrimaryKey(<#list primaryKeyColumns as column><#if column_index != 0> , </#if> ${column.javaType} ${column.propertyName?uncap_first} </#list>)throws Exception{
    int totalRecords=0;
    <#if plugin.enableMybatisplus>
        totalRecords+= ${mapperName?uncap_first}.deleteById(<#list primaryKeyColumns as column> <#if column_index != 0> , </#if> ${column.propertyName?uncap_first} </#list>);
    <#else >
        totalRecords+=${mapperName?uncap_first}.delete${modelName}ByPrimaryKey(<#list primaryKeyColumns as column> <#if column_index != 0> , </#if> ${column.propertyName?uncap_first} </#list>);

    </#if>


    return totalRecords;

    }
</#if>

<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
    /**
    * 通过主键删除多条${remarksTable}数据
    **/
    public int delete${modelName}ByIds(<#list primaryKeyColumns as column><#if column_index != 0> , </#if> String [] ${column.propertyName?uncap_first}s </#list>)throws Exception{
    int totalRecords=0;
    <#if plugin.enableMybatisplus>
        totalRecords+= ${mapperName?uncap_first}.deleteBatchIds(<#list primaryKeyColumns as column><#if column_index != 0> , </#if>     Arrays.asList( ${column.propertyName?uncap_first}s) </#list>);
    <#else >
        totalRecords+=${mapperName?uncap_first}.delete${modelName}ByIds(<#list primaryKeyColumns as column><#if column_index != 0> , </#if>      StringUtils.join( ${column.propertyName?uncap_first}s, ",") </#list>);

    </#if>
   return totalRecords;


    }
</#if>


<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
    /**
    * 更新${remarksTable}数据
    **/
    public  int update${modelName}ByPrimaryKey(${modelName} record)throws Exception{
    int totalRecords = 0;

    ${modelName}    ${modelName?uncap_first}Old= select${modelName}ByPrimaryKey(<#list primaryKeyColumns as column><#if column_index != 0> , </#if> record.get${column.propertyName}() </#list>);
    <#list columns as  column>
        <#if column.isPrimary!="true">
             ${modelName?uncap_first}Old.set${column.propertyName}(record.get${column.propertyName}()); // ${column.remark}
        </#if>

    </#list>


    <#if plugin.enableMybatisplus>
        totalRecords += ${mapperName?uncap_first}.alwaysUpdateSomeColumnById(record);
    <#else >
        totalRecords += ${mapperName?uncap_first}.update${modelName}ByPrimaryKey(record);

    </#if>

    return totalRecords;

    }
</#if>
<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0 && primaryKeyColumns?size == 1)>
    /**
    * 批量更新属性不为空${remarksTable}数据
    **/
    <#list primaryKeyColumns as column>
    public  int update${modelName}ByPrimaryKeyNotNull(${modelName} record, String[] ${column.propertyName?uncap_first}s) throws Exception{
    int totalRecords = 0;
        if(${column.propertyName?uncap_first}s==null || ${column.propertyName?uncap_first}s.length<0){
        if(record.get${column.propertyName?cap_first}()!=null){
        ${column.propertyName?uncap_first}s=new String[]{String.valueOf(record.get${column.propertyName?cap_first}())};
        }
        }
        if(${column.propertyName?uncap_first}s!=null || ${column.propertyName?uncap_first}s.length>0) {

        for (String ${column.propertyName?uncap_first}:${column.propertyName?uncap_first}s){
        record.set${column.propertyName?cap_first}(${column.javaType}.valueOf(${column.propertyName?uncap_first}));

        <#if plugin.enableMybatisplus>
            totalRecords += ${mapperName?uncap_first}.updateById(record);
        <#else >
            totalRecords += ${mapperName?uncap_first}.update${modelName}ByPrimaryKeyNotNull(record);

        </#if>


        }
        }

    return totalRecords;

    }
    </#list>
</#if>

<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
    /**
    * 通过主键查询${remarksTable}数据
    **/
    public  ${modelName} select${modelName}ByPrimaryKey(<#list primaryKeyColumns as column><#if column_index != 0> , </#if> ${column.javaType} ${column.propertyName?uncap_first} </#list>){

    <#if plugin.enableMybatisplus>
        ${modelName} data=  ${mapperName?uncap_first}.selectById(<#list primaryKeyColumns as column><#if column_index != 0> , </#if>  ${column.propertyName?uncap_first} </#list>);
    <#else >
        ${modelName} data=  ${mapperName?uncap_first}.select${modelName}ByPrimaryKey(<#list primaryKeyColumns as column><#if column_index != 0> , </#if>  ${column.propertyName?uncap_first} </#list>);

    </#if>
     return data;
    }
</#if>


/**
* 通过条件查询${remarksTable}数据
**/
public List<${modelName}> select${modelName}(${modelName} ${modelName?uncap_first}, String desc, String startTime, String endTime, String notNullAttributes,
String isNullAttributes, String globalSearch,String likeNameSearch, Double amountSearch, String universalTime,String multipleChoiceCondition, String fieldConditionStr){
    Parameter<${modelName}> parameter = new Parameter<>();


    parameter.setData(${modelName?uncap_first});
    parameter.setDesc(desc);

    parameter.setStartTime(startTime);
    parameter.setEndTime(endTime);
    parameter.setAmountSearch(amountSearch);
    ParameterUtil parameterUtil = new ParameterUtil();
    parameterUtil.notNullAttributes = notNullAttributes;
    parameterUtil.isNullAttributes = isNullAttributes;
    parameterUtil.globalSearch = globalSearch;
    parameterUtil.likeNameSearch = likeNameSearch;
    parameterUtil.amountSearch = amountSearch;
    parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
    parameterUtil.universalTime = universalTime;
    parameterUtil.fieldConditionStr = fieldConditionStr;
    parameterUtil.setParameterValue(parameter);

    List<${modelName}> list =${mapperName?uncap_first}.select${modelName}(parameter);
    return list;
}

/**
*总条数
**/
public long get${modelName}PageCount(${modelName} ${modelName?uncap_first}, String desc, String startTime,
String endTime, String notNullAttributes,
String isNullAttributes, String globalSearch,String likeNameSearch, Double amountSearch, String universalTime,String multipleChoiceCondition, String fieldConditionStr){
    Parameter<${modelName}> parameter = new Parameter<>();


    parameter.setData(${modelName?uncap_first});
    parameter.setDesc(desc);

    parameter.setStartTime(startTime);
    parameter.setEndTime(endTime);
    parameter.setAmountSearch(amountSearch);
    ParameterUtil parameterUtil = new ParameterUtil();
    parameterUtil.notNullAttributes = notNullAttributes;
    parameterUtil.isNullAttributes = isNullAttributes;
    parameterUtil.globalSearch = globalSearch;
    parameterUtil.likeNameSearch = likeNameSearch;
    parameterUtil.amountSearch = amountSearch;
    parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
    parameterUtil.universalTime = universalTime;
    parameterUtil.fieldConditionStr = fieldConditionStr;
    parameterUtil.setParameterValue(parameter);
    long l =${mapperName?uncap_first}.get${modelName}PageCount(parameter);
    return l;


}
/**
* 分页条件查询${remarksTable}
**/
public Pager<${modelName}> get${modelName}Page(long curPage, int pageSize, String
orderBy, ${modelName} ${modelName?uncap_first}, String desc, String startTime, String endTime, String
notNullAttributes,
String isNullAttributes, String globalSearch,String likeNameSearch, Double amountSearch, String universalTime,String multipleChoiceCondition, String fieldConditionStr,String isLimit){
    Parameter<${modelName}> parameter = new Parameter<>();

    parameter.setOrderBy(orderBy);
    parameter.setData(${modelName?uncap_first});
    parameter.setDesc(desc);
    parameter.setPageSize(pageSize);
    parameter.setStartTime(startTime);
    parameter.setEndTime(endTime);
    parameter.setIsLimit(isLimit);
    parameter.setAmountSearch(amountSearch);
    ParameterUtil parameterUtil = new ParameterUtil();
    parameterUtil.notNullAttributes = notNullAttributes;
    parameterUtil.isNullAttributes = isNullAttributes;
    parameterUtil.globalSearch = globalSearch;
    parameterUtil.likeNameSearch = likeNameSearch;
    parameterUtil.amountSearch = amountSearch;
    parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
    parameterUtil.universalTime = universalTime;
    parameterUtil.fieldConditionStr = fieldConditionStr;
    parameterUtil.setParameterValue(parameter);

    Pager<${modelName}>   pager =null;
    if(!StrUtil.isEmpty(isLimit)&&isLimit.equals("false")){
        pager = new Pager(0, pageSize, curPage);
        pager.setCode(0);
        pager.setMsg("查询成功");
        List<${modelName}> list = ${mapperName?uncap_first}.get${modelName}Page(parameter);
        pager.setDatas(list);
     }else{
            long totalRecords =${mapperName?uncap_first}.get${modelName}PageCount(parameter);
            pager = new Pager(totalRecords, pageSize, curPage);
            pager.setCode(0);
            pager.setMsg("查询成功");
            if (totalRecords > 0) {
            parameter.setStartIndex(pager.getStartIndex());
            parameter.setEndIndex(pager.getEndIndex());
            List<${modelName}> list = ${mapperName?uncap_first}.get${modelName}Page(parameter);
            pager.setDatas(list);
        }
    }




    return pager;
}
    /**
    * 导出表格中字段
    * @param attributeMap
    */
    public void setAttributeMap(LinkedHashMap${r"<"}String, String> attributeMap) {

        <#list columns as column>
            <#if column.isPrimary=="false">

                attributeMap.put("${column.remark}", "${column.propertyName?uncap_first}");
            </#if>

        </#list>



    }

    /**
    * 导出${remarksTable}模板
    *
    * @throws Exception
    */
    @Override
    public void exportSpSupplierTemplate() throws Exception {
        LinkedHashMap${r"<"}String, String> attributeMap = new LinkedHashMap<>();
        setAttributeMap(attributeMap);



        Map${r"<"}String, String[]> dropDownBoxAttributeMap = new HashMap<>();



        HSSFWorkbook workbook = PoiExport.createWorkbookTitleRow("信息", "${remarksTable}信息", attributeMap, dropDownBoxAttributeMap, null);

        PoiExport.responseFile(workbook, response, "${remarksTable}模板.xlsx");
    }


    /**
    * 导出供应商
    * @param orderBy 以什么排序
    * @param ${modelName?uncap_first}
    * @param desc 是否降序排序
    * @param startTime 开始时间
    * @param endTime 结束时间
    * @param notNullAttributes 不为空筛选  多个,分割
    * @param isNullAttributes 为空筛选 多个
    * @param globalSearch
    * @param likeNameSearch 模糊查询 格式 {字段:'条件'}
    * @param amountSearch 数值模糊查询
    * @param universalTime 时间 格式 {字段:{startTime:'',endTime:''}}
    * @param multipleChoiceCondition 多选条件格式 {字段:[数据,数据]}
    * @param fieldConditionStr 高级查询json 格式[{databaseId:'',relationId:'',datas:[]}]
    * @throws Exception
    */
    @Override
    public void exportSpSupplier(String orderBy, ${modelName} ${modelName?uncap_first}, String desc, String startTime, String endTime, String notNullAttributes, String isNullAttributes, String globalSearch, String likeNameSearch, Double amountSearch, String universalTime, String multipleChoiceCondition, String fieldConditionStr) throws Exception {
    Parameter${r"<"}${modelName}> parameter = new Parameter<>();

        parameter.setOrderBy(orderBy);
        parameter.setData(${modelName?uncap_first});
        parameter.setDesc(desc);
        parameter.setIsLimit("false");
        parameter.setStartTime(startTime);
        parameter.setEndTime(endTime);
        parameter.setAmountSearch(amountSearch);
        ParameterUtil parameterUtil = new ParameterUtil();
        parameterUtil.notNullAttributes = notNullAttributes;
        parameterUtil.isNullAttributes = isNullAttributes;
        parameterUtil.globalSearch = globalSearch;
        parameterUtil.likeNameSearch = likeNameSearch;
        parameterUtil.amountSearch = amountSearch;
        parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
        parameterUtil.universalTime = universalTime;
        parameterUtil.fieldConditionStr = fieldConditionStr;
        parameterUtil.setParameterValue(parameter);

        List<${modelName}> list = ${modelName?uncap_first}Mapper.get${modelName}Page(parameter);


            LinkedHashMap${r"<"}String, String> attributesMap = new LinkedHashMap<>();
<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
            <#list primaryKeyColumns as column>
                attributesMap.put("${column.remark}", "${column.propertyName?uncap_first}");
            </#list>
</#if>

            setAttributeMap(attributesMap);

            Set${r"<"}String> attributeKeys = attributesMap.keySet();
                List${r"<"}String> attributeKeyList = new ArrayList<>(attributeKeys);




                    Map${r"<"}String, String[]> dropDownBoxAttributeMap = new HashMap<>();


                    String sheetName = "信息";
                    HSSFWorkbook workbook = PoiExport.createWorkbookTitleRow(sheetName, "${remarksTable}信息", attributesMap, dropDownBoxAttributeMap, null);
                    HSSFSheet sheet = workbook.getSheet(sheetName);


                    HSSFCellStyle strStyle = PoiExport.strStyle(workbook, null);
                    HSSFCellStyle strStyle2 = PoiExport.strStyle2(workbook, null);
                    HSSFCellStyle datestyle = PoiExport.Datestyle(workbook, null);
                    HSSFFont firstFont = workbook.createFont();
                    firstFont.setFontName("宋体");
                    firstFont.setFontHeightInPoints((short) 11);
                    firstFont.setColor(IndexedColors.RED.getIndex());
                    firstFont.setBold(true);
                    HSSFCellStyle firstCellStyle = PoiExport.firstCellStyle(workbook, firstFont);
                    HSSFFont hjFont = workbook.createFont();
                    hjFont.setFontName("宋体");
                    hjFont.setFontHeightInPoints((short) 11);
                    HSSFCellStyle hjCellStyle = workbook.createCellStyle();
                    hjCellStyle.setBorderBottom(BorderStyle.THIN);
                    hjCellStyle.setBorderRight(BorderStyle.THIN);
                    hjCellStyle.setAlignment(HorizontalAlignment.CENTER);
                    hjCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    hjCellStyle.setWrapText(true);
                    hjCellStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));
                    hjCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
                    hjCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    hjCellStyle.setFont(hjFont);
                    HSSFCellStyle BigDecimalstyle = PoiExport.BigDecimalstyle(workbook);
                    Map${r"<"}String, HSSFCellStyle> cellStyleMap = new HashMap<>();
                    cellStyleMap.put("String", strStyle);
                    cellStyleMap.put("BigDecimal", BigDecimalstyle);
                    cellStyleMap.put("Date", datestyle);

                    int lastRow = sheet.getLastRowNum();
                    for (${modelName} data : list) {


                        lastRow += 1;
                        HSSFRow rowData = sheet.createRow(lastRow);
                        for (int i = 0; i < attributeKeyList.size(); i++) {
                        String attributeKeyName = attributeKeyList.get(i);
                        String fieldName = attributesMap.get(attributeKeyName);
                        HSSFCell cell = rowData.createCell(i);
                        Object value = null;


                        value = Tool.getFieldByClass(fieldName, data);



                        PoiExport.setCellValue(cell, value, cellStyleMap);
                    }


                    }

                    PoiExport.responseFile(workbook, response);


                    }

    /**
    * 导入供应商数据
    *
    * @param file
    * @throws Exception
    */
    @Override
    public void import${modelName}(MultipartFile file) throws Exception {
        LinkedHashMap${r"<"}String, String> attributesMap = new LinkedHashMap<>();
<#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
        <#list primaryKeyColumns as column>
            attributesMap.put("${column.remark}", "${column.propertyName?uncap_first}");
        </#list>
</#if>
        setAttributeMap(attributesMap);
        Set${r"<"}String> attributeKeys = attributesMap.keySet();
            List${r"<"}String> attributeKeyList = new ArrayList<>(attributeKeys);

                Map${r"<"}String, String> reverse = MapUtil.reverse(attributesMap);


                List${r"<"}String> specialHandlingFields = new ArrayList<>();//需要特殊处理字段


                    List${r"<"}String> canBeEmptyFields = new ArrayList<>();// 跳过判空

                    <#list primaryKeyColumns as column>

                        canBeEmptyFields.add("${column.propertyName?uncap_first}");

                    </#list>



                        Workbook workBook = null;
                        PoiReadUtil${r"<"}${modelName}> poiReadUtil = new PoiReadUtil();
                            workBook = poiReadUtil.readWorkbookData(workBook, file, attributesMap, specialHandlingFields, canBeEmptyFields, ${modelName}.class);
                            CellStyle cellStyleBk = PoiExport.strStyleRed(workBook, null);
                            CellStyle strStyleBrown = PoiExport.strStyleBrown(workBook, null);

                            List${r"<"}PoiReadUtil${r"<"}${modelName}>.PoiReadData> poiReadDataList = poiReadUtil.getPoiReadDataList();
                                int numberOfFailures = poiReadUtil.getNumberOfFailures();//失败行数
                                int totalRecords = 0;
                                for (PoiReadUtil${r"<"}${modelName}>.PoiReadData data : poiReadDataList) {
                                    try {
                                    boolean isSuccess = true;
                                    ${modelName}  ${modelName?uncap_first} = data.getModelData();

                                    LinkedHashMap${r"<"}String, Map${r"<"}String, String>> attributesMapI = data.getAttributesMapI();//所有表头位置
                                    LinkedHashMap${r"<"}String, Map${r"<"}String, String>> attributesMapL = data.getAttributesMapL();//所有表头位置

                                    int rowIndex = data.getRowIndex();//数据在表格中行
                                    int sheetIndex = data.getSheetIndex();//第几个工作表
                                    Sheet sheet = workBook.getSheetAt(sheetIndex);
                                    Row row = sheet.getRow(rowIndex);
                                    Map${r"<"}String, Object> specialHandlingFieldMap = data.getSpecialHandlingFieldMap();//需要特殊处理的字段及值
                                    if (specialHandlingFieldMap != null && specialHandlingFieldMap.size() > 0) {
                                    Set${r"<"}String> specialHandlingFieldKey = specialHandlingFieldMap.keySet();


                                        for (String key : specialHandlingFieldKey) {
                                        Object value = specialHandlingFieldMap.get(key);
                                        if (value == null) continue;
                                        String attributeName = reverse.get(key);

                                        Map${r"<"}String, String> map = attributesMapL.get(attributeName);
                                        String index = map.get("index");
                                        Cell cell = row.getCell(Integer.parseInt(index));

                                        String s = value.toString().trim();
                                        try {


                                        } catch (Exception e) {
                                        e.printStackTrace();
                                        numberOfFailures += 1;
                                        isSuccess = false;

                                        if (cell == null) {
                                        cell = row.createCell(Integer.parseInt(index));
                                        }
                                        cell.setCellStyle(cellStyleBk);
                                        continue;
                                        }


                                        }
                                        }

                                        if (${modelName?uncap_first} == null || !isSuccess) {
                                        numberOfFailures += 1;
                                        continue;

                                        }



                <#if primaryKeyColumns ?has_content  && (primaryKeyColumns?size > 0)>
                                        <#list primaryKeyColumns as column>

                                            ${column.javaType} ${column.propertyName?uncap_first} = ${modelName?uncap_first}.get${column.propertyName}();

                                        </#list>
                                        if (
                                            <#list primaryKeyColumns as column>
                                                <#if column_index != 0> && </#if>
                                                <#if column.javaType=="String" > !StrUtil.isEmpty(${column.propertyName?uncap_first})
                                                <#else>
                                                    ${column.propertyName?uncap_first} !=null
                                                </#if>

                                                </#list>


                                                ) {

                    <#if plugin.enableMybatisplus>
                        totalRecords += ${mapperName?uncap_first}.updateById(${modelName?uncap_first});
                    <#else >
                        totalRecords += ${mapperName?uncap_first}.update${modelName}ByPrimaryKeyNotNull(${modelName?uncap_first});

                    </#if>

                                        } else {

                                        totalRecords += insert${modelName}(${modelName?uncap_first});

                                        sheet.removeRow(row);


                                        }
                            </#if>
                                        } catch (Exception e) {
                                        e.printStackTrace();
                                        numberOfFailures += 1;
                                        }


                                        }
                                        PrintWriter out = null;
                                        try {
                                        PoiExport.importReturn(numberOfFailures, response, workBook, out, totalRecords);
                                        } catch (Exception e) {
                                        e.printStackTrace();
                                        } finally {
                                        if (out != null) {
                                        out.close();
                                        }
                                        if (workBook != null) {
                                        workBook.close();
                                        }
                                        }
                                    }

}